package org.csu.myProject.web.servlet;

import org.csu.myProject.domain.User;
import org.csu.myProject.service.UserService;
import org.csu.myProject.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserInfoServlet extends HttpServlet {
    private static final String LOGIN_FORM = "/WEB-INF/jsp/login.jsp";
    private static final String INFO_JSP = "/WEB-INF/jsp/info.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User loginUser = (User)session.getAttribute("loginUser");

        if(loginUser == null)
        {
            req.setAttribute("msg", "请先登录");
            req.getRequestDispatcher(LOGIN_FORM).forward(req,resp);
        }else{
            if(loginUser.isAdmin())
            {
                int id = Integer.parseInt(req.getParameter("id"));
                UserService userService = new UserServiceImpl();
                User userInfo = userService.getUserInfo(id);
                session.setAttribute("userInfo", userInfo);
            }else{
                session.setAttribute("userInfo", loginUser);
            }
            req.getRequestDispatcher(INFO_JSP).forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
